//
//  JSCommentViewController.m
//  danpin
//
//  Created by chuangjia on 7/11/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "JSCommentViewController.h"
#import "JSCommentCell.h"
#import "SVPullToRefreshView+OY_PullRefreshView.h"
#import "SVHTTPRequest.h"
#import "OtherUserCenterVC.h"
#import "ZShare.h"
#import "HcCustomKeyboard.h"

@interface JSCommentViewController ()<UITableViewDataSource,UITableViewDelegate,HcCustomKeyboardDelegate,UIActionSheetDelegate>
{
    
}
@property(nonatomic,strong)UITableView *tbView;
@property(nonatomic,strong)NSMutableArray *sectionArray;
@property(nonatomic,assign)int currentPage;
@property(nonatomic,assign)BOOL isLoadFinished;
@property(nonatomic,assign)BOOL isRequesting;
@property(nonatomic,assign)BOOL isRefresh;
@property(nonatomic,assign)int  commentType;
@property(nonatomic,strong)NSDictionary*  commentDictionary;
@property(nonatomic,strong)NSDictionary*  clickedDictionary;
@end

@implementation JSCommentViewController
@synthesize tbView=_tbView;
@synthesize sectionArray=_sectionArray;
@synthesize currentPage=_currentPage;
@synthesize commentId=_commentId;
@synthesize content_object=_content_object;
@synthesize commentType=_commentType;
@synthesize commentDictionary=_commentDictionary;
@synthesize clickedDictionary=_clickedDictionary;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navTitle = @"全部评论";
    if (!_sectionArray) {
        _sectionArray =[[NSMutableArray alloc] init];
    }
    self.isLoadFinished =NO;
    self.isRequesting = NO;
    self.currentPage = 1;
    _commentType=0;
    [self initUI];

//    [ZShare showAnimationView:self.view center:CGPointZero];
    [self getShopBalanceList];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[SVHTTPClient sharedClient] cancelAllRequests];
    self.tbView = nil;
    [HcCustomKeyboard customKeyboard].mDelegate=nil;
    [[HcCustomKeyboard customKeyboard].mTextView removeFromSuperview];
    [HcCustomKeyboard customKeyboard].mTextView=nil;
    [[HcCustomKeyboard customKeyboard].mTextView resignFirstResponder];
}

-(void)initUI
{
    _tbView = [[UITableView alloc] initWithFrame:CGRectMake(0, hightAuto(65), self.view.bounds.size.width, self.view.bounds.size.height-hightAuto(65)-40) style:UITableViewStylePlain];
    _tbView.delegate = self;
    _tbView.dataSource = self;
    _tbView.backgroundColor =UIColorFromRGB(0xf8f8f8);
    _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tbView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:_tbView];
    // setup infinite scrolling
    __weak typeof (self) wSelf = self;
    self.currentPage = 1;
    [_tbView addPullToRefreshWithActionHandler:^{
        wSelf.isRequesting = YES;
        wSelf.isRefresh = NO;
        wSelf.currentPage = 1;
        wSelf.isLoadFinished = NO;
        [wSelf.tbView.pullToRefreshView startAnimating];
        [wSelf getShopBalanceList];
    }];
    //
    //
    [_tbView.pullToRefreshView setOYStyle];
    //
    // setup infinite scrolling
    [self.tbView addInfiniteScrollingWithActionHandler:^{
        if (wSelf.isRequesting) {
            return ;
        }
        
        if (wSelf.isLoadFinished) {
            //停止菊花
            //   [wSelf.tbView.infiniteScrollingView stopAnimating];
            //
            return;
        }
        
        wSelf.isRefresh = NO;
       // [wSelf.tbView setShowsInfiniteScrolling:YES];
        [wSelf.tbView.infiniteScrollingView startAnimating];
        [wSelf  getShopBalanceList];
        
    }];
    //
     [[HcCustomKeyboard customKeyboard] textViewShowView:self customKeyboardDelegate:self];
}
#pragma mark - tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_sectionArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row>=_sectionArray.count) {
        return 40;
    }
    NSDictionary *dict = [_sectionArray objectAtIndex:indexPath.row];
    return [JSCommentCell returnCellHeight:dict];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JSCommentCell *cell = (JSCommentCell*)[tableView  dequeueReusableCellWithIdentifier:@"JSCommentCell"];//重用cell啊！！！
    if(cell == nil)
    {
        cell = [[JSCommentCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
        cell.backgroundColor=[UIColor whiteColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        __weak typeof (self) wSelf = self;
        [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
            [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
        }];
    }
    if (indexPath.row>=_sectionArray.count) {
        return cell;
    }
    NSDictionary *dict = [_sectionArray objectAtIndex:indexPath.row];
    [cell showInfo:dict key:@"JSCommentCell" indexPath:indexPath];
    return cell;
}
-(void)cellAction:(BEventType)type views:(UIView *)v obj:(id)obj key:(id)key indexPath:(NSIndexPath *)indexPath
{
    _clickedDictionary = [NSMutableDictionary dictionaryWithDictionary:obj];
    switch (type) {
        case BEventType_sunUser:
        {
                
            id user_info = [obj objectForKey:@"user_info"];
            if (user_info && [user_info isKindOfClass:[NSDictionary class]])
            {
                NSString *userid =[[NSString stringWithFormat:@"%@",[user_info objectForKey:@"id"]] replaceNullString];
                NSString *largeFace =[[NSString stringWithFormat:@"%@",[user_info objectForKey:@"avatar200"]] replaceNullString];
                NSString *nick_name =[[NSString stringWithFormat:@"%@",[user_info objectForKey:@"nickname"]] replaceNullString];
                
                OtherUserCenterVC *user =[[OtherUserCenterVC alloc] init];
                NSMutableDictionary *dict =[NSMutableDictionary dictionary];
                [dict setValue:[NSString stringWithFormat:@"%@",largeFace] forKey:@"largeFace"];
                [dict setValue:[NSString stringWithFormat:@"%@",userid] forKey:@"user_id"];
                [dict setValue:[NSString stringWithFormat:@"%@",nick_name] forKey:@"nick_name"];
                user.userDictionary=dict;
                [self.navigationController pushViewController:user animated:YES];
                return;
            }
        }
            break;
        case BEventType_comment:
        {
            if ([self isLogin]) {
                UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                              initWithTitle:nil
                                              delegate:self
                                              cancelButtonTitle:@"取消"
                                              destructiveButtonTitle:nil
                                              otherButtonTitles:@"回复",@"@TA",@"举报",nil];
                actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
                [actionSheet showInView:self.view];
            }

        }
            break;
        case BEventType_cai:
        {
            if ([self isLogin]) {
                _commentDictionary =[NSMutableDictionary dictionaryWithDictionary:obj];
                [self dingcaijubao:@"-1"];
            }
        }
            break;
        case BEventType_ding:
        {
            if ([self isLogin]) {
                _commentDictionary =[NSMutableDictionary dictionaryWithDictionary:obj];
                [self dingcaijubao:@"1"];
            }
        }
            break;
        case BEventType_report:
        {
            if ([self isLogin]) {
                _commentDictionary =[NSMutableDictionary dictionaryWithDictionary:obj];
                [self dingcaijubao:@"-2"];
            }
            
        }break;
        case BEventType_at:
        {
            _commentType = 2;
            _commentDictionary =[NSMutableDictionary dictionaryWithDictionary:obj];
            id user =[_commentDictionary objectForKey:@"user_info"];
            if (user && [user isKindOfClass:[NSDictionary class]]) {
                NSString *username = [user objectForKey:@"nickname"];
                NSString *name =[NSString stringWithFormat:@"@%@ ", username];
                [[HcCustomKeyboard customKeyboard].mTextView  becomeFirstResponder];
                [HcCustomKeyboard customKeyboard].mTextView.text =name;
            }
            
        }
            break;
        case BEventType_reply:
        {
            _commentType = 3;
            _commentDictionary =[NSMutableDictionary dictionaryWithDictionary:obj];
            [[HcCustomKeyboard customKeyboard].mTextView  becomeFirstResponder];
            
        }break;
            
        default:
            break;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row>=_sectionArray.count) {
        return;
    }
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
        {
            if ([self isLogin]) {
                _commentType = 3;
                _commentDictionary =[NSMutableDictionary dictionaryWithDictionary:_clickedDictionary];
                [[HcCustomKeyboard customKeyboard].mTextView  becomeFirstResponder];
            }
        }
            break;
        case 1:
        {
            if ([self isLogin]) {
                _commentType = 2;
                _commentDictionary =[NSMutableDictionary dictionaryWithDictionary:_clickedDictionary];
                id user =[_commentDictionary objectForKey:@"user_info"];
                if (user && [user isKindOfClass:[NSDictionary class]]) {
                    NSString *username = [user objectForKey:@"nickname"];
                    NSString *name =[NSString stringWithFormat:@"@%@ ", username];
                    [[HcCustomKeyboard customKeyboard].mTextView  becomeFirstResponder];
                    [HcCustomKeyboard customKeyboard].mTextView.text =name;
                }
            }
        }
            break;
        case 2:
        {
            if ([self isLogin]) {
                _commentDictionary =[NSMutableDictionary dictionaryWithDictionary:_clickedDictionary];
                [self dingcaijubao:@"-2"];
            }
        }
            break;
        case 3:
        {
            
        }
            break;
        default:
            break;
    }
}
//====================================================
//
//====================================================
-(void)getShopBalanceList
{
    
    self.isRequesting =YES;
    __weak typeof (self) wSelf = self;
    NSString *strURL =[NSString stringWithFormat:@"http://dpapi.mgpyh.com/api/v1/get_post_comment/?source=dp&post_id=%@&post_type=1&page=%@%@",self.commentId,[NSString stringWithFormat:@"%d",_currentPage],[ZShare publicParams]];
    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [SVHTTPRequest GET:strURL parameters:nil completion:^(id response, NSHTTPURLResponse *urlResponse, NSError *error)
     {
         if (urlResponse.statusCode==401) {
             [[ZToastManager ShardInstance] showtoast:@"用户状态异常，请重新登录！"];
             [[ZShare sharedInstance] setUserInfo:nil];
             return ;
         }
         if (response==nil) {
             return ;
         }
         if (error==nil) {
             [wSelf parserResultObject:response];
             wSelf.isRequesting = NO;
             wSelf.isRefresh =NO;
             [wSelf.tbView.pullToRefreshView stopAnimating];
             [wSelf.tbView.infiniteScrollingView stopAnimating];
         //    [ZShare hiddenAnimationView:wSelf.view];
         }else{
             wSelf.isRequesting = NO;
             wSelf.isRefresh =NO;
             [wSelf.tbView.pullToRefreshView stopAnimating];
             [wSelf.tbView.infiniteScrollingView stopAnimating];
         //    [ZShare hiddenAnimationView:wSelf.view text:@""];
         }
     }];
}
-(void)parserResultObject:(id)resultObject
{
 //   [ZShare hiddenAnimationView:self.view];
    if (resultObject==nil) {
        return;
    }
    if (resultObject && [resultObject isKindOfClass:[NSDictionary class]]) {
        id data =  [resultObject objectForKey:@"items"];
        if (data && [data isKindOfClass:[NSArray class]]){
            if (self.currentPage ==1) {
        
                [self.sectionArray removeAllObjects];
            }
            for (NSDictionary *dict in data) {
                [self.sectionArray addObject:dict];
            }
        }
        int nextpage = [[resultObject objectForKey:@"nextpage"] intValue];
        int total_count = [[resultObject objectForKey:@"total_count"] intValue];
        if (self.sectionArray.count>=total_count) {
            self.isLoadFinished = YES;
        }else{
            self.currentPage = nextpage;
            self.isLoadFinished = NO;
        }
        if (self.isLoadFinished) {
          
            NSString *end_msg =[resultObject objectForKey:@"end_msg"];
            self.tbView.tableFooterView =[ZShare footerView:end_msg];
            
            [self.tbView.infiniteScrollingView stopAnimating];
            [self.tbView setShowsInfiniteScrolling:NO];
        }
        else
        {
            self.tbView.tableFooterView =nil;
            [self.tbView setShowsInfiniteScrolling:YES];
        }
    }
    [self.tbView reloadData];
}
//=========================================
//
//=========================================
//
-(void)talkBtnClick:(UITextView *)textViewGet
{
    if(textViewGet.text.length==0)
    {
        [[ZToastManager ShardInstance] showtoast:@"请输入内容"];
        return;
    }
    NSString *commentcontent = [NSString stringWithFormat:@"%@",textViewGet.text];
    
    if ([self isLogin]) {
        if(_commentType ==3)
        {
            NSString *cmit =[[NSString stringWithFormat:@"%@",[_commentDictionary objectForKey:@"comment_id"]] replaceNullString];
            [self commentWithPostId:self.commentId  commentId:cmit context:commentcontent];
        }else{
            [self commentWithPostId:self.commentId  commentId:@"" context:commentcontent];
        }
        
    }
}
-(void)commentWithPostId:(NSString*)pid commentId:(NSString*)commit context:(NSString*)content
{
    __weak typeof (self) wSelf = self;
    NSDictionary *userinfo =(NSDictionary*)[ZShare sharedInstance].userInfo;
    NSString *api_key =[[NSString stringWithFormat:@"%@",[ZShare sharedInstance].api_key] replaceNullString];
    NSString *user_name =[[NSString stringWithFormat:@"%@",[userinfo objectForKey:@"nick_name"]] replaceNullString];
    
    NSString *strURL =[NSString stringWithFormat:@"http://dpapi.mgpyh.com/api/dp/mobilecomment/?api_key=%@&username=%@",api_key,user_name];
    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableDictionary *param =[NSMutableDictionary dictionary];
    [param setValue:content forKey:@"comment"];
    [param setValue:_content_object forKey:@"content_object"];
    [param setValue:pid forKey:@"object_pk"];
    if (commit.length>0) {
         NSString *co = [NSString stringWithFormat:@"/api/dp/mobilecomment/%@/",commit];
         [param setValue:co forKey:@"parent"];
    }
    [param setValue:@"dp" forKey:@"source"];
    [param setValue:@"8c580ca5fbb52de883c7f1b471c923c4355e9932" forKey:@"security_hash"];
    [param setValue:@"1433149751" forKey:@"timestamp"];
    NSString *params = [ZShare DataTOjsonString:param];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *url = [NSURL URLWithString:strURL];
        //第二步，创建请求
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPMethod:@"POST"];
        //设置参数
        NSData *data = [params dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:data];
        //
        
        NSOperationQueue *queue = [[NSOperationQueue alloc]init];
        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
            if (data==nil) {
                return ;
            }
            NSDictionary* dcRes = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//            NSLog(@"commentWithPostId=====>%@",dcRes);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (dcRes) {
                    [[ZToastManager ShardInstance] showtoast:@"评论成功！"];
                  
                }
                if(_tbView)
                {
                    [_tbView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
                }
                wSelf.currentPage = 1;
                [wSelf getShopBalanceList];
                
                id  comment_js =[dcRes objectForKey:@"comment_js"];
                if (comment_js && [comment_js isKindOfClass:[NSString class]]) {
                     [[NSNotificationCenter defaultCenter] postNotificationName:@"updatejs" object:comment_js];
                }
            });
            
        }];
    });
    
}
///=================
/*
【顶，踩，举报】：后端请求，根据api_key
V3
dpapi.mgpyh.com/api/dp/mobilevote/?api_key=&username=

{"target_object": "/api/dp/mobilecomment/595158/", "flag": -2}

flag = 1 ： 顶 flag=-1 : 踩  flag=-2举报
需要评论ID 同评论*/
//==================
-(void)dingcaijubao:(NSString *)flag
{
    __weak typeof (self) wSelf = self;
    NSDictionary *userinfo =(NSDictionary*)[ZShare sharedInstance].userInfo;
    NSString *api_key =[[NSString stringWithFormat:@"%@",[ZShare sharedInstance].api_key] replaceNullString];
    NSString *user_name =[[NSString stringWithFormat:@"%@",[userinfo objectForKey:@"nick_name"]] replaceNullString];
    NSString *cmit =[[NSString stringWithFormat:@"%@",[_commentDictionary objectForKey:@"comment_id"]] replaceNullString];
    NSString *strURL =[NSString stringWithFormat:@"http://dpapi.mgpyh.com/api/dp/mobilevote/?api_key=%@&username=%@",api_key,user_name];
    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableDictionary *param =[NSMutableDictionary dictionary];
    [param setValue:flag forKey:@"flag"];
    [param setValue:[NSString stringWithFormat:@"/api/dp/mobilecomment/%@/",cmit] forKey:@"target_object"];
    NSString *params = [ZShare DataTOjsonString:param];
    
//    NSLog(@"【顶，踩，举报】===%@---%@",strURL,params);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *url = [NSURL URLWithString:strURL];
        //第二步，创建请求
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPMethod:@"POST"];
        //设置参数
        NSData *data = [params dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:data];
        //
        
        NSOperationQueue *queue = [[NSOperationQueue alloc]init];
        [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
            if (data==nil) {
                return ;
            }
            NSDictionary* dcRes = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
           NSLog(@"commentWithPostId=====>%@",dcRes);
            dispatch_async(dispatch_get_main_queue(), ^{
                wSelf.currentPage = 1;
                int code = [[dcRes objectForKey:@"code"] intValue];
                if (code==801) {
                    [wSelf modifyDictionary:cmit flag:[flag intValue] flag_count:@"" add:NO];
                }else{
                    NSString *flag_count = [[NSString stringWithFormat:@"%@",[dcRes objectForKey:@"flag_count"]] replaceNullString];
                    [wSelf modifyDictionary:cmit flag:[flag intValue] flag_count:flag_count add:YES];
                }
                id  comment_js =[dcRes objectForKey:@"comment_js"];
                if (comment_js && [comment_js isKindOfClass:[NSString class]]) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"updatejs" object:comment_js];
                }
             
            });
            
        }];
    });
}
-(void)modifyDictionary:(NSString*)cmid flag:(int)flag flag_count:(NSString *)flag_count add:(BOOL)isadd
{
    for (int i=0; i<self.sectionArray.count; i++) {
        NSDictionary *dict = [self.sectionArray objectAtIndex:i];
        NSString *commit = [[NSString stringWithFormat:@"%@",[dict objectForKey:@"comment_id"]] replaceNullString];
        
        if ([cmid isEqualToString:commit]) {
            NSMutableDictionary *temp = [dict mutableCopy];
            if (flag==1) { //顶
                 NSString *up_vote = [[NSString stringWithFormat:@"%@",[dict objectForKey:@"up_vote"]] replaceNullString];
                if (isadd) {
                    [temp setValue:flag_count forKey:@"up_vote"];
                }else{
                    if ([up_vote intValue]==0) {
                        [temp setValue:@"0" forKey:@"up_vote"];
                    }else{
                        [temp setValue:[NSString stringWithFormat:@"%d",[up_vote intValue]-1] forKey:@"up_vote"];
                    }
                }
                
            }else if (flag==-1) //踩
            {
                NSString *down_vote = [[NSString stringWithFormat:@"%@",[dict objectForKey:@"down_vote"]] replaceNullString];
               
                if (isadd) {
                     [temp setValue:flag_count forKey:@"down_vote"];
                }else{
                    if ([down_vote intValue]==0) {
                         [temp setValue:@"0" forKey:@"down_vote"];
                    }else{
                        [temp setValue:[NSString stringWithFormat:@"%d",[down_vote intValue]-1] forKey:@"down_vote"];
                    }
                }
            }
            [self.sectionArray replaceObjectAtIndex:i withObject:temp];
            break;
        }
    
    }
    [_tbView reloadData];
}
@end

